package com.java2104.controller;

import com.java2104.entity.Document;
import com.java2104.entity.User;
import com.java2104.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/document")
public class DocumentController {
    @Autowired
    private DocumentService documentService;

    @PostMapping(path = "/delete",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String delete(@RequestBody List<Integer> ids,HttpServletResponse response){
        int n = documentService.delete(ids);
        response.setContentType("text/html;charset=utf-8");
        return "成功删除了" + n + "个文档";
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(Document document){
        documentService.update(document);
        return "success";
    }

    @RequestMapping("/edit/{eId}")
    public String edit(@PathVariable Integer eId, Model model) throws IOException{
        model.addAttribute("document",documentService.get(eId));
        return "document/showUpdateDocument";
    }

    @RequestMapping("/download/{docId}")
    public void download(@PathVariable Integer docId, HttpServletResponse response) throws IOException {
        Map map = documentService.getFileInputStream(docId);
        String filename = URLEncoder.encode((String)map.get("filename"),"UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + filename);
        if(map!=null){
            FileCopyUtils.copy((InputStream) map.get("stream"),response.getOutputStream());
        }
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(String title, String remark, @RequestParam("file") MultipartFile file,
                         @SessionAttribute("loginUser") User loginUser) throws IOException {
        Document document = new Document();
        document.setTitle(title);
        document.setRemark(remark);
        document.setCreateUser(loginUser);
        documentService.save(document,file);
        return "Document upload successfully!" +
                "<a href='/doucment/showAddDocument.jsp'>Continue Upload!</a> or" +
                "<a href='/document/document.jsp'>To search the Doc!</a>";
    }
    @RequestMapping("/list")
    @ResponseBody
    public List<Document> list(String title){
        return documentService.getList(title);
    }
}
